import { createRouter, createWebHistory } from 'vue-router'
import login from '../views/login/login.vue'
import mainbox from '../views/mainbox/mainbox.vue'
import arr from '@/router/config'
import notfound from '@/views/404.vue'
//vue3在路由route.js中获取不到仓库pinia中store里面的值
//原因：小仓库(useUserStore )必须有大仓库(pinia)才能运行，在组件中能使用pinia仓库的数据，
//是因为在main.ts中已经在vue上面挂载了大仓库(pinia)，但是route.js不是vue组件，没有被挂载大仓库，所以不能运行
import {pinia} from '@/stores/counter'
import  {useCounterStore}  from '@/stores/counter.js'
const Counter = useCounterStore(pinia)


const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/login',
      name: 'login',
      component: login
    },
    {
      path: '/mainbox',
      name: 'mainbox',
      component: mainbox
    },
    {
      path:'/',
      redirect:'/home'
    },
    {
      path:'/:pathmatch(.*)*',
      component:notfound
    }
  ]
})

//路由守卫
router.beforeEach((to,form,next)=>{
  //判断是否为登录页
  if(to.name == 'login'){
    next()
  }else{
    //判断是否登录成功
    if(localStorage.getItem('token')){
      //判断是否第一次配置动态路由
      if(!Counter.first){
        arr.forEach(item=>{
          router.addRoute('mainbox',item)
        })
        Counter.change()
        //导航到指定页面
        next({path:to.fullPath})
      }
      else{
        next()
      }
    }else{
      next({path:'/login'})
    }
  }
  
})
export default router
